package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.mapper.PermissionMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.util.PageResult;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;

@Service
public class PermissionServiceImpl implements IPermissionService {
    @Autowired
    private PermissionMapper mapper;
    @Autowired
    RequestMappingHandlerMapping rmhm;

    public List<Permission> selectAll() {
        return mapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int count = mapper.query4Count(qo);
        if (count > 0) {
            return new PageResult(count, mapper.query4List(qo));
        }
        return new PageResult(count, Collections.EMPTY_LIST);
    }


    public void insert(Permission record) {
        mapper.insert(record);
    }

    public void reload() {
        List<String> allResource = mapper.getAllResource();
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = rmhm.getHandlerMethods();
        Collection<HandlerMethod> methods = handlerMethods.values();
        for (HandlerMethod method : methods) {
            //判断获取到的有RequestMapping注解的方法中有没有贴的RequiredPermission注解
            RequiresPermissions annotation = method.getMethodAnnotation(RequiresPermissions.class);
            if(annotation!=null){
                //添加权限到数据库
                String[] values = annotation.value();
                if(!allResource.contains(values[0])){
                Permission p = new Permission();
                p.setName(values[1]);
                p.setResource(values[0]);
                mapper.insert(p);
                }
            }
        }

    }

    public Set<String> selectPermissionByEmployeeId(Long id) {
        return mapper.selectPermissionByEmployeeId(id);
    }


}
